package com.wing.wcabinet.controller.admin;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.order.model.entity.OrderReceiveLoad;
import com.wing.order.model.request.OrderReceiveLoadForm;
import com.wing.wcabinet.model.entity.WcabCellInventoryInout;
import com.wing.wcabinet.model.response.WcabCellLoadVO;
import com.wing.wcabinet.service.WcabCellInventoryInoutDetailService;
import com.wing.web.annotation.RequestObjectFieldIgnore;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.wcabinet.model.entity.WcabCellLoad;
import com.wing.wcabinet.model.request.WcabCellLoadForm;
import com.wing.wcabinet.service.WcabCellLoadService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author
 */
@Validated
@Api(value = "Admin-上货数量管理", tags = "#/wcabinet/wcabCellLoad")
@RestController("wcabCellLoadController")
@RequestMapping("wcabinet/admin/wcabCellLoad")
@RequiredArgsConstructor
@Slf4j
public class WcabCellLoadController {

    private final WcabCellLoadService wcabCellLoadService;

    @Autowired
    private WcabCellInventoryInoutDetailService wcabCellInventoryInoutDetailService;


    @ApiOperation(value = "查询所有上货数量", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "sort", value="排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "order", value="排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
    })
    @GetMapping("/list")
    public PageResult<WcabCellLoadVO> list(
            @RequestParam(defaultValue = "1") Integer page
            ,@RequestParam(defaultValue = "10") Integer limit
            ,@RequestParam(defaultValue = "create_time") String sort
            ,@RequestParam(defaultValue = "desc") String order
            ,Long receiveDetailId
            ,String code
            ,String startTime
            ,String endTime
    ){

        Page<WcabCellLoad> pg = new Page<>(page, limit);
        Map<String, Object> params = new HashMap<>();

        //排序
        if (StringUtils.isNotBlank(sort) && StringUtils.isNotBlank(order)) {
            params.put("sort", StrUtil.toUnderlineCase(sort));
            params.put("order", order);
        }
        params.put("receiveDetailId",receiveDetailId);
        params.put("code",code);
        //搜索
        params.put("startCreateTime",startTime);
        params.put("endCreateTime",endTime);
        params.put("operationType",WcabCellLoad.OperationType.load);
        IPage<WcabCellLoadVO> list = wcabCellLoadService.pageList(pg,params);
        return new PageResult<>(list.getRecords(), list.getTotal());
    }



    @ApiOperation(value = "添加上货数量", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/add")
    public JsonResult add(@Validated(WcabCellLoadForm.Add.class) WcabCellLoadForm wcabCellLoadForm) {
        if (wcabCellLoadService.add(wcabCellLoadForm) > 0) {
            return JsonResult.success("添加成功");
        }
        return JsonResult.fail("添加失败");
    }




    @ApiOperation(value = "修改上货数量", notes = "修改")
    @PutMapping("/update")
    public JsonResult update(@Validated(WcabCellLoadForm.Update.class) WcabCellLoadForm wcabCellLoadForm) {
        WcabCellLoad wcabCellLoad = wcabCellLoadService.getById(wcabCellLoadForm.getId());
        if(wcabCellLoad == null){
        return JsonResult.fail("修改失败！");
        }
        CopyOptions copyOptions = CopyOptions.create()
        .setEditable(WcabCellLoad.class)
        .setIgnoreError(true)
        .setIgnoreNullValue(true);
        BeanUtil.copyProperties(wcabCellLoadForm, wcabCellLoad, copyOptions);
        if (wcabCellLoadService.updateById(wcabCellLoad)) {
            return JsonResult.success("修改成功！");
        }
        return JsonResult.fail("修改失败！");
    }



    @ApiOperation(value = "删除上货数量", notes = "删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "wcabCellLoadId", value = "上货数量id", required = true, dataType = "Integer", paramType = "path")
    })
    @DeleteMapping("/detail/{id}" )
    public JsonResult delete(@PathVariable("id") Long wcabCellLoadId) {
        if (wcabCellLoadService.removeById(wcabCellLoadId)) {
            return JsonResult.success("删除成功");
        }
        return JsonResult.fail("删除失败");
    }

    @ApiOperation(value = "上货", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/load")
    public JsonResult wcabLoad(@Validated(WcabCellLoadForm.Add.class) @RequestBody WcabCellLoadForm orderReceiveLoadForm) {
        try{
            orderReceiveLoadForm.setType(WcabCellLoad.Type.selfBatchLoadSimple);
            orderReceiveLoadForm.setOperationType(WcabCellLoad.OperationType.load);
            wcabCellInventoryInoutDetailService.inventoryIn4Batch(orderReceiveLoadForm);
            return JsonResult.success("上货成功");
        }catch (Exception e){
            log.error("receive load fail",e);
            return JsonResult.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "下货", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/unload")
    public JsonResult wcabUnload(@Validated(WcabCellLoadForm.Add.class)@RequestBody WcabCellLoadForm orderReceiveLoadForm) {
        try{
            log.info("unload param:{}", JSON.toJSONString(orderReceiveLoadForm));
            orderReceiveLoadForm.setType(WcabCellLoad.Type.selfBatchUnloadSimple);
            orderReceiveLoadForm.setOperationType(WcabCellLoad.OperationType.unload);
            wcabCellInventoryInoutDetailService.inventoryOut4Batch(orderReceiveLoadForm);
            return JsonResult.success("下货成功");
        }catch (Exception e){
            log.error("receive load fail",e);
            return JsonResult.fail(e.getMessage());
        }
    }
}
